<template>

    <view :style="themeColor()">
        <view class="bg-[var(--page-bg-color)] min-h-[100vh]" v-if="orderData">
            <view class="pt-[30rpx] sidebar-margin payment-bottom">
                <!-- 配送方式 -->

                <view class="mb-[var(--top-m)] card-template   ">
                    <view class="card-template-item">
                        <view class="text-[32rpx] w-[150rpx] leading-[30rpx] text-[#303133]">补录日期</view>
                        <view class="flex-1 flex w-0 text-right  price-font text-[#333] text-[32rpx] ">
                            <uni-datetime-picker v-model="createData.repairDate" :border="false" type="date"
                                :end="new Date().getTime()" />
                            <text class="nc-iconfont nc-icon-youV6xx text-[var(--text-color-light9)] ml-[2rpx]"></text>

                        </view>

                    </view>
                    <view class="card-template-item">
                        <view class="text-[32rpx] w-[150rpx] leading-[30rpx] text-[#303133]">收款员工</view>
                        <view class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx] flex justify-end">
                            <text class="text-[32rpx] text-gray-subtitle"> {{ createData.rebateType == 0 ? '默认' :
                                '指定'
                            }}
                            </text>
                            <text class="nc-iconfont nc-icon-youV6xx text-[var(--text-color-light9)] ml-[2rpx]"></text>

                        </view>
                    </view>
                    <view class="card-template-item" v-if="createData.rebateType == 1">
                        <view class="text-[32rpx] w-[150rpx] leading-[30rpx] text-[#303133]">选择员工</view>
                        <view
                            class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx] flex justify-end items-center"
                            @click="employeeRef.open(createData.employeeStr)">
                            <view class=" flex justify-end truncate">
                                <text v-if="createData.employeeStr && createData.employeeStr.length"
                                    class=" text-[32rpx]  ">
                                    {{ cartEmployeeText }}
                                </text>
                                <text class="text-[32rpx] text-gray-subtitle" v-else>请选择员工</text>
                            </view>
                            <text class="nc-iconfont nc-icon-youV6xx text-[var(--text-color-light9)] ml-[2rpx]"></text>
                        </view>
                    </view>

                </view>
                <view class="mb-[var(--top-m)] card-template p-[0] pb-[var(--pad-top-m)]">
                    <view class="py-[var(--pad-top-m)]">
                        <view class="mb-[20rpx] " v-for="(item, index) in orderData.goods" :key="item.spuId"
                            :class="{ 'border-[4rpx] border-[#ef000c] rounded-[8rpx] pb-[20rpx] border-solid': item.spuType == 3 }">
                            <!-- 商品 -->
                            <view class="flex px-[20rpx] ">

                                <u--image radius="var(--goods-rounded-big)" width="180rpx" height="180rpx"
                                    :src="img(item.sku.picUrl)" model="aspectFill">
                                    <template #error>
                                        <image
                                            class="w-[180rpx] h-[180rpx] rounded-[var(--goods-rounded-big)] overflow-hidden"
                                            :src="img('static/resource/images/diy/shop_default.jpg')" mode="aspectFill">
                                        </image>
                                    </template>
                                </u--image>
                                <view class="flex flex-1 w-0 flex-col justify-between ml-[20rpx] py-[6rpx]">
                                    <view class="line-normal">
                                        <view class="truncate text-[#303133] font-bold text-[32rpx] leading-[38rpx]">


                                            {{ item.titleName || item.spuName }}
                                        </view>
                                        <view class="flex items-center mt-[14rpx]">
                                            <view class=" flex mr-[8rpx]" v-if="item?.spu.specType">
                                                <text class="truncate text-[24rpx]  leading-[32rpx]">{{
                                                    skuSpecFormat(item?.sku.properties)
                                                }} /</text>
                                            </view>
                                            <template v-if="item?.spu.spuType == 2">
                                                <text class="text-[24rpx] text-[var(--price-text-color)]">{{
                                                    filterCardAttributes(item.sku, true, true) }}</text>
                                            </template>
                                        </view>

                                    </view>
                                    <view class="flex items-center flex-wrap mt-[8rpx]">


                                        <!-- <view class="text-[24rpx] text-[var(--price-text-color)] leading-[34rpx] "
                                            v-if="item.leavePrice > 0">
                                            剩余欠款: ￥{{ diyGoods.fen2yuan(item.leavePrice) }}
                                        </view> -->
                                    </view>
                                    <view class="flex justify-between items-baseline">

                                        <view class="text-[var(--price-text-color)] flex items-baseline  price-font">
                                            <text class="text-[24rpx] font-500 text-[#303133] mr-[4rpx]">剩余欠款：</text>

                                            <text class="text-[24rpx] font-500 mr-[4rpx]">￥</text>
                                            <text class="text-[30rpx] font-500">{{
                                                parseFloat(diyGoods.fen2yuan(item.leavePrice)).toFixed(2).split('.')[0]
                                            }}</text>
                                            <text class="text-[24rpx] font-500">.{{
                                                parseFloat(diyGoods.fen2yuan(item.leavePrice)).toFixed(2).split('.')[1]
                                            }}</text>

                                        </view>

                                    </view>
                                </view>
                            </view>



                        </view>
                    </view>
                    <!-- 买家留言 -->
                    <view class="bg-white flex items-center leading-[30rpx] px-[var(--pad-sidebar-m)]">
                        <view class="text-[32rpx] w-[150rpx] text-[#303133]">备注</view>
                        <view class="flex-1 text-[#303133]">
                            <input type="text" v-model="createData.member_remark"
                                class="text-right text-[#333] text-[32rpx]" maxlength="50" placeholder="请输入订单备注"
                                placeholder-class="text-[var(--text-color-light9)] text-[32rpx]">
                        </view>
                    </view>


                </view>




                <view class="card-template">
                    <view class="title !text-[32rpx]">价格明细</view>
                    <view class="card-template-item">
                        <view class="text-[32rpx] w-[170rpx] leading-[30rpx] text-[#303133]">剩余欠款</view>
                        <view class="flex-1 w-0 text-right  price-font text-[#333] text-[32rpx]">
                            ￥{{ parseFloat(diyGoods.fen2yuan(orderData?.price?.totalPrice)).toFixed(2) }}
                        </view>
                    </view>




                </view>
            </view>
            <u-tabbar :fixed="true" :placeholder="true" :safeAreaInsetBottom="true" zIndex="10">
                <view class="flex-1 flex items-center justify-between pl-[30rpx] pr-[20rpx]">
                    <view class="flex items-baseline">
                        <text class="text-[32rpx] text-[#333] leading-[32rpx]">本次还款：</text>
                        <view class="inline-block">
                            <text
                                class="text-[32rpx] font-500 text-[var(--price-text-color)] price-font leading-[30rpx]">￥</text>
                            <text
                                class="text-[44rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">{{
                                    parseFloat(diyGoods.fen2yuan(orderData?.price?.payPrice)).toFixed(2).split('.')[0]
                                }}</text>
                            <text
                                class="text-[32rpx]  font-500  text-[var(--price-text-color)] price-font leading-[46rpx]">.{{
                                    parseFloat(diyGoods.fen2yuan(orderData?.price?.payPrice)).toFixed(2).split('.')[1]
                                }}</text>
                        </view>
                        <text @click="handleChangePrice"
                            class="nc-iconfont nc-icon-xiugaiV6xx text-[32rpx] text-[var(--price-text-color)] ml-10rpx"></text>

                    </view>
                    <button :loading="createLoading"
                        class="w-[250rpx]  h-[84rpx] font-500 text-[32rpx] leading-[84rpx] !text-[#fff] m-0  rounded-full  primary-btn-bg remove-border"
                        hover-class="none" @click="create">提交订单</button>
                </view>
            </u-tabbar>


        </view>

        <!-- 选择员工 -->
        <select-employee ref="employeeRef" @confirm="confirmSelectEmployee" />


        <!-- 整单改价弹框 -->
        <price-change-popup ref="priceChangeRef" v-if="orderData" @confirm="setPayPrice" />
        <!-- 现金支付 欠款支付 线上支付 根据不同按钮进行不同的支付方式展示 -->
        <select-payment ref="selectPaymentRef" v-if="orderData" :order-info="orderData" :sceneType="'second'"
            :payment-map="payDialogClassify" @confirm="onSelectPaymentPay" @confirm-order="confirmOrder"
            @success="handleUpdate"></select-payment>



    </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted } from 'vue'
import { editCart, addRepay } from '@/addon/shop/api/cart';
import { getPayInfo } from '@/app/api/pay'


import { secondSettlementOrder, repayOrderCreate, getShopOrderDetail, getSystemConfigByKey } from '@/addon/shop/api/order'
import { redirect, img, moneyFormat, mobileHide, goback } from '@/utils/common'

import priceChangePopup from '@/addon/components/repayment-price-change-popup/repayment-price-change-popup.vue';
import selectPayment from '@/addon/components/select-payment/select-payment.vue';

import { onShow, onUnload } from '@dcloudio/uni-app'
import { cloneDeep } from 'lodash-es'
import { useGoods } from '@/addon/shop/hooks/useGoods'

const diyGoods = useGoods();

import { skuSpecFormat, formatSkuType, formatSpuType, filterCardAttributes } from '@/utils/formatting'

const createData: any = ref({
    order_key: '',
    member_remark: '',
    discount: {},
    invoice: {},
    delivery: {
        delivery_type: '0'
    },
    extend_data: {}, // 扩展数据，拼团价用到
    // ========== 补录 ==========
    isRepair: false, //是否补录
    repairDate: undefined, //补录日期
    // ========== 分成 ==========
    rebateType: 1, //0统一 1单一
    // ========== 员工 ==========
    employeeStr: [],
    // ========== 密码 ==========
    enalePassword: false, // 开启密码支付 true是
    password: undefined,//支付密码
    // =======支付======
    pay: [] as any,
    // 购物车订单号 
    no: "",

})

const orderData: any = ref({
    goods: [] as any, // 商品项列表
    paymentMap: [] as any,
    payOrderId: '',
    price: { totalPrice: 0, payPrice: 0 } as any // 价格信息
})

const employeeRef = ref()
const createLoading = ref(false)
uni.getStorageSync('orderCreateData') && Object.assign(createData.value, uni.getStorageSync('orderCreateData'))
console.log(createData.value)
onShow(() => {
    const options = uni.getEnterOptionsSync();
    // scene 1038	从另一个小程序返回
    // #ifdef MP
    if (options.scene == 1038) {
        uni.$emit('scene', {
            scene: 1038
        })
        return
    }
    // #endif

})
onUnload(() => {
    uni.$off('scene')
})


/**
 * 选择支付方式
 */
const selectPaymentRef = ref()
const handleSelectPayment = () => {

    selectPaymentRef.value.open()
}




/** 真实支付 现金支付 线上支付 后置支付 */
const payDialogClassify = computed(() => {
    return postfClassify.value
})
const postfClassify = computed(() => {
    const insideGroup = orderData.value.paymentMap.filter((ele: any) => {
        return (
            ele.group == 'other' || (ele.group == 'mock' && !['coupon', 'debt'].includes(ele.classify))
        )
    }) as any

    return insideGroup || []
}) as any
/**
 * 修改本次还款金额
 */
const priceChangeRef = ref()

const handleChangePrice = () => {
    priceChangeRef.value.open(orderData.value.price)
}

const setPayPrice = (price: any) => {
    orderData.value.price.payPrice = price.balance
}
// 选择资产支付
const onSelectPaymentPay = async (item: any, classify: any) => {
    let params = {
        classify: classify,
        payStatus: item.payStatus,
        paybalance: item.paybalance,
        assetsId: item.assetsId,
        usingDis: item.usingDis
    }
    // 当前所使用的 对应支付类型的支付列表
    createData.value.pay = [params]

    console.log('选择资产支付')

}

const handleUpdate = async () => {
    uni.showToast({
        title: '订单完成',
        icon: 'success'
    })
    let goBackParameter = {
        url: '/addon/shopMemberInfo/pages/index',
        title: '订单完成',
        mode: 'reLaunch'
    };
    goback(goBackParameter)

}






const cartEmployeeText = computed(() => {
    let employeeText = '';
    if (createData.value.rebateType == 1) {
        createData.value.employeeStr.forEach((element: any, index: any) => {
            if (index == createData.value.employeeStr.length - 1) {
                employeeText += element.employeeName + ' ' + element.proportion + '%';
            } else {
                employeeText += element.employeeName + ' ' + element.proportion + '%' + '|';
            }
        });
    }
    return employeeText;
});



const confirmSelectEmployee = (employee: any) => {
    if (createData.value.rebateType == 1) {
        createData.value.employeeStr = employee
        if (autoConfirm.value) {
            create()

        }
    }
}



/**
 * 订单计算
 */
const calculate = (payOrderId: any) => {
    console.log('loading')
    let params = {
        payOrderId: payOrderId,

    }

    secondSettlementOrder(params).then(({ data }: any) => {
        // 优惠券
        orderData.value.paymentMap = data.paymentMap; //购买商品
        orderData.value.payOrderId = data.payOrderId
        orderData.value.price = data.price
        console.log(orderData.value)
        handleSelectPayment()





    }).catch(
        (error) => {
            console.log(error)
            let goBackParameter = {
                url: '/addon/shopMemberInfo/pages/index',
                title: error.msg,
                mode: 'reLaunch'
            };
            goback(goBackParameter)

        }
    )
}
const getRepaymentList = () => {
    addRepay({ orderItemIds: createData.value.cart_ids }).then(({ data }: any) => {
        console.log(data)
        orderData.value.goods = data.validList

        orderData.value.price.totalPrice = data.repayPrice
        orderData.value.price.payPrice = data.repayPrice
        console.log(orderData.value)



    }).catch((err) => {

    })


}
onMounted(() => {
    // calculate()
    getRepaymentList()

})



// let orderId = 0
const autoConfirm = ref(false) //自动提交

/**
 * 订单创建
 */
const create = () => {
    if (!verify() || createLoading.value) return

    // if (orderData.value.price.payPrice == 0) {
    //     confirmOrder()
    // } else {
    //     handleSelectPayment()

    // }
    confirmOrder()

    // useSubscribeMessage().request('shop_order_pay,shop_order_delivery')

}

/**订单提交 */
const confirmOrder = () => {
    if (!verify() || createLoading.value) return

    if (createData.value.repairDate && !createData.value.member_remark) {
        uni.showToast({ title: "请输入备注信息", icon: 'none' });

        return
    }
    // if (createData.value.enalePassword && !createData.value.password) {
    //     passwordRef.value.open()
    //     return
    // }
    // if (!createData.value.enalePassword && !createData.value.password) {
    //     let params = {
    //         scene: 0,
    //         code: ''
    //     }
    //     passwordRef.value.confirm(params)
    //     return
    // }
    createLoading.value = true
    let items = [] as any
    orderData.value.goods.map((item: any) => {
        items.push({
            skuId: item.skuId,
            count: item.count,
            cartId: item.id
        })
    })

    let params = {
        items: items,
        deliveryType: 0,

        remark: createData.value.member_remark,
        // authToken: createData.value.password, //密码
        rebateType: createData.value.rebateType, //分成类型
        employeeStr: createData.value.employeeStr, //员工
        isRepair: createData.value.repairDate ? 1 : 0, //是否补录
        repairDate: createData.value.repairDate, //补录日期
        repayPrice: orderData.value.price.payPrice,


    }
    repayOrderCreate(params).then(async ({ data }: any) => {
        if (data.payOrderId) {
            let merchantOrderId = data.id
            let payOrderId = data.payOrderId
            calculate(payOrderId)
            // checkPayStatus(merchantOrderId, payOrderId, 'confirm')

        }
        console.log(data)

    }).catch(() => {
        createData.value.password = ""
        createLoading.value = false
    })

}

/**
 * 下单校验
 */
const verify = () => {
    const data = createData.value

    let verify = true
    if (true) {
        if (cartEmployeeText.value == '') {

            if (data.rebateType == 1) {
                autoConfirm.value = true

                employeeRef.value.open([])
            }

            return false
        }


    }
    return verify
}









</script>

<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

:deep(.u-tabbar) {
    .u-tabbar__content {

        .u-tabbar__content__item-wrapper {
            height: 120rpx !important;

        }
    }
}

.head-tab {
    .head-tab-item {
        .tab-image {
            left: 50%;
            transform: translateX(-50%);
        }

        &:nth-child(1).active {
            view {
                padding-right: 40rpx;
            }
        }

        &:nth-child(2) {
            .tab-image {
                width: 312rpx;
            }
        }

        &:nth-child(3).active {
            view {
                padding-left: 30rpx;
            }
        }

        &.active {
            view {
                font-weight: bold;
                color: var(--primary-color);
            }
        }

        .tab-img {
            left: 50%;
            transform: translateX(-50%);
        }

    }
}

:deep(.u-alert) {
    padding: 6rpx 16rpx !important;
    display: inline-block !important;
}

.alert-wrap {
    display: inline-block !important;

    :deep(.u-fade-enter-active) {
        display: inline-block !important;
    }
}

.text-ellipsis {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
}

.line-normal {
    line-height: normal;
}

.bg-color {
    background: linear-gradient(94deg, var(--primary-help-color) 0%, var(--primary-color) 69%), var(--primary-color);
}

:deep(.uni-date__x-input) {
    height: unset;
    line-height: 1;
}

:deep(.u-action-sheet) {
    .u-line {
        margin: 0 30rpx !important;
        width: auto !important;
        border-color: #ddd !important;
    }

    .u-action-sheet__cancel {
        padding: 0;

    }

    .u-action-sheet__item-wrap__item__name {
        font-size: 30rpx !important;
    }
}

.payment-bottom {
    padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}
</style>
